import {
  SUB_PAGES
} from "../config/router.config"

export const SELECT_TYPE = {
  dept: {
    text: '科室',
    num: 0
  },
  user: {
    text: '人',
    num: 0
  },
  team: {
    text: '小组',
    num: 0
  },
  dic: {
    text: '种',
    num: 0
  }
}

export const keyDept = "dept"
export const keyTeam = "team"
export const keyUser = "user"
export const keyDic = "dic"

/**
 * 将科室数据重写
 * @param {*} arr 
 */
export function deptToConvert(arr) {
  return arr.map((item) => {
    return {
      ...item,
      _value: `${item.deptId}`,
      _name: item.deptName,
      _key: keyDept,
    }
  })
}
/**
 * 将字典数据重写
 * @param {*} arr 
 */
export function dicToConvert(arr) {
  return arr.map((item) => {
    return {
      ...item,
      //  _value: `${perfixDicValue}${item.dictValue}`,
      _value: `${item.dictValue}`,
      _name: item.dictLabel,
      _key: keyDic,
    }
  })
}
/**
 * 将 科室和小组和人员的列表 转换为只有小组和人员
 * @param {*} arr 
 */
export function deptAndTeamToConvert(arr) {
  const list = arr.map(item => item.teamList)
  const _list = wx.$_.flatten(list)
  console.log(_list, 'arr');
  const result = [];
  _list.forEach(team => {
    const team_value = team.teamId;
    const user_list = [];
    team.userList.forEach(user => {
      const user_value = user.userId;
      user_list.push({
        _path: `${user.nickName}/${team.teamName}`,
        userId: user.userId,
        nickName: user.nickName,
        _value: user_value,
        _key: keyUser,
        _name: user.nickName,
        _teamId: team_value
      });
    });

    result.push({
      _key: keyTeam,
      _name: team.teamName,
      _value: team_value,
      _path: `${team.teamName}`,
      _teamId: team_value,
      teamId: team_value,
      teamName: team.teamName,
      userList: user_list,
      children: user_list

    });

  });

  return result
}


/**
 * 将 科室和小组和人员的列表坐一个重写
 * @param {*} arr 
 */
export function deptAndGroupAndUserToConvert(arr) {
  const result = [];
  arr.forEach(dept => {
    const dept_value = dept.deptId
    const team_list = [];
    dept.teamList.forEach(team => {
      const team_value = team.teamId;
      const user_list = [];

      team.userList.forEach(user => {
        const user_value = user.userId;

        user_list.push({
          _path: `${user.nickName}/${team.teamName}/${dept.deptName}`,
          userId: user.userId,
          nickName: user.nickName,
          _teamId: team_value,
          _value: user_value,
          _key: keyUser,
          _name: user.nickName,
        });
      });

      team_list.push({
        _key: keyTeam,
        _name: team.teamName,
        _value: team_value,
        _path: `${team.teamName}/${dept.deptName}`,
        _teamId: team_value,
        teamId: team.teamId,
        teamName: team.teamName,
        userList: user_list,
        children: user_list

      });
    });
    result.push({
      _path: dept.deptName,
      _key: keyDept,
      _value: dept_value,
      _name: dept.deptName,
      _teamId: '',
      deptId: dept.deptId,
      deptName: dept.deptName,
      teamList: team_list,
      children: team_list
    });
  });
  return result
}

/**
 * 平铺tree
 * @param {*} tree 
 */
export function flattenTree(tree) {
  const result = [];

  function traverse(node) {

    for (const child of node) {
      result.push(child);
      if (child.children && child.children.length > 0) {
        traverse(child.children);
      }
    }
  }
  traverse(tree);
  return result;
}


/**
 * 计算选中不同类型的数据
 * 比如 科室 小组 人员
 * @param {*} arr 
 */
export function selectedTypeNumComputed(arr, sourceData = []) {
  const filterValue = sourceData.filter(item => arr.includes(item._value))
  const selected = {
    dept: {
      text: '科室',
      num: 0
    },
    user: {
      text: '人',
      num: 0
    },
    team: {
      text: '小组',
      num: 0
    },
    dic: {
      text: '种',
      num: 0
    }
  }


  for (let i of filterValue) {
    selected[i._key].num += 1

  }
  return selected


}

/**
 * 处理checkbox值选中
 * @param {*} checkValue 选择的值
 * @param {*} isCheck  是否选中
 * @param {*} originList  已选择值的列表
 */
export function handleCheckBoxChecked(checkValue, isCheck, originList) {
  const index = wx.$_.indexOf(originList, checkValue)
  //  存在
  if (index > -1) {
    //  取消选中情况
    if (!isCheck) {
      originList.splice(index, 1)
    }
  } else {
    originList.push(checkValue)
  }
  return originList
}
/**
 * 处理复杂数据的选中
 * @param {*} checkValue 
 * @param {*} isCheck 
 * @param {*} originList 
 */
export function handleChecked(checkValue, isCheck, originList, key = "id") {
  const index = wx.$_.findIndex(originList, (item) => item[key] === checkValue[key])
  //  存在
  if (index > -1) {
    //  取消选中情况
    if (!isCheck) {
      originList.splice(index, 1)
    }
  } else {
    originList.push(checkValue)

  }
  return originList
}

/**
 * 获取每个键对应数组的长度并计算总和
 * @param {*} obj 
 */
export function keyArrLength(obj) {
  let totalLength = 0;
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const arr = obj[key];
      const length = arr.length;
      totalLength += length;
    }
  }
  return totalLength
}
export function objToArr(obj) {
  let arr = []
  for (let i in obj) {
    arr.push(val[i])
  }
  return arr
}

/**
 * 将 map 结构转为平铺结构
 */
export function mapToArr(obj) {
  let arr = []
  for (let i in obj) {
    arr = [...arr, ...obj[i]]
  }
  return arr
}

/**
 * 处理选中 用于selectedPopup组件
 * @param {*} sourceData  源数据
 * @param {*} val  选择的值
 */
export function handleSelectedPopup(sourceData, val) {
  const filterList = wx.$_.filter(sourceData, (item) => val.includes(item._value))
  let selectedPopupList = {}
  for (let i of filterList) {
    const {
      _key,
      _name,
      _value
    } = i
    selectedPopupList[_key] = selectedPopupList[_key] || [];
    selectedPopupList[_key].push({
      name: _name,
      value: _value,
      key: _key
    });
  }
  return selectedPopupList
}

/**
 * 将扁平数据转换成树形数据
 * @param data
 * @param config
 * @returns {unknown[]}
 */
export function convertToTree(data, config = {
  id: 'deptId',
  parentId: 'parentId',
  name: 'name'
}) {
  const tree = {};
  const map = {};
  const arr = JSON.parse(JSON.stringify(data));
  arr.forEach((item) => {
    const id = item[config.id];
    const pid = item[config.parentId];
    Object.assign(item, {
      _path: item[config.name]
    })
    map[id] = item;
    if (pid !== 0 && pid) {
      const parent = map[pid];
      if (parent) {
        parent['children'] = parent.children || [];
        const parentPath = parent._path || '';
        const path = `${parentPath}/${item[config.name]}`;
        Object.assign(item, {
          _path: path
        })
        parent.children.push(item);
      }
    } else {
      tree[id] = item;
    }
  });
  if (wx.$_.isEmpty(tree)) {
    return Object.values(map);
  }
  return Object.values(tree);
}

/**
 * 截取文件名称
 * 用于附件上传
 * @param {*} name 
 * @param {*} len 
 */
export function interceptFileName(name, len = 20) {
  return name.substring(name.length - len)
}

/**
 * 提取文件名称后缀
 */
export function fileSuffix(fileName) {
  const regex = /\.([^.]+)$/;
  const match = fileName.match(regex);
  return match[1]
}
// 获取当前页面路径
export function getCurrentPage() {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const url = `/${currentPage.route}`;
  return url
}

/** 
 * 跳转至选择人员页面
 */
export function toUserSelectPage(backToPath, key, multiple = true, confirmFn) {
  const params = {
    backToPath,
    key,
    multiple
  }
  wx.navigateTo({
    url: `${SUB_PAGES.Filter.FILTER_USER_SELECT.router}${queryParams(params)}`,
    events: {
      confirm: confirmFn
    },
    success() {

    },
    fail(fail) {
      console.error(fail);
    }
  })

}
/**
 * 跳转至选择科室页面
 * @param {*} backToPath 
 * @param {*} storeKey 
 * @param {*} choseType    selectDept,selectDeptTeamUser,selectTeamUser
 * @param {*} multiple 
 */
export function toDeptSelectPage(backToPath, storeKey, choseType, multiple) {
  const params = {
    backToPath,
    storeKey,
    choseType,
    multiple
  }
  wx.navigateTo({
    url: `${SUB_PAGES.Filter.FILTER_DEPT_SELECT.router}${queryParams(params)}`,
  })
}

/**
 * 跳转至字典选择页面
 * @param {*} backToPath 
 * @param {*} key 
 * @param {*} multiple 
 */
export function toDicSelectPage(backToPath, storeKey, dicKey, multiple = true) {
  const params = {
    backToPath,
    dicKey,
    storeKey,
    multiple
  }
  wx.navigateTo({
    url: `${SUB_PAGES.Filter.FILTER_DIC_SELECT.router}${queryParams(params)}`,
  })
}
/**
 * 处理对于人员,科室筛选路由参数统一化
 */
export function handleFilterRouter(backToPath, choseType, globalDataKey, dicKey, multiple = true) {
  return `backToPath=${backToPath}&choseType=${choseType}&globalDataKey=${globalDataKey}&dicKey=${dicKey}&multiple=${multiple}`
}

/**
 * 处理arr删除
 */
export function handleDelChecked(value, checkedValue, key = "val") {
  let index = wx.$_.findIndex(checkedValue, (item) => item[key] === value)
  console.log(index, checkedValue, 'handleDelChecked');
  if (index > -1) {
    checkedValue.splice(index, 1)
  }
  return checkedValue

}

export function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
  const prefix = isPrefix ? '?' : ''
  const _result = []
  if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets'
  for (const key in data) {
    const value = data[key]
    // 去掉为空的参数
    if (['', undefined, null].indexOf(value) >= 0) {
      continue
    }
    // 如果值为数组，另行处理
    if (value.constructor === Array) {
      // e.g. {ids: [1, 2, 3]}
      switch (arrayFormat) {
        case 'indices':
          // 结果: ids[0]=1&ids[1]=2&ids[2]=3
          for (let i = 0; i < value.length; i++) {
            _result.push(`${key}[${i}]=${value[i]}`)
          }
          break
        case 'brackets':
          // 结果: ids[]=1&ids[]=2&ids[]=3
          value.forEach((_value) => {
            _result.push(`${key}[]=${_value}`)
          })
          break
        case 'repeat':
          // 结果: ids=1&ids=2&ids=3
          value.forEach((_value) => {
            _result.push(`${key}=${_value}`)
          })
          break
        case 'comma':
          // 结果: ids=1,2,3
          let commaStr = ''
          value.forEach((_value) => {
            commaStr += (commaStr ? ',' : '') + _value
          })
          _result.push(`${key}=${commaStr}`)
          break
        default:
          value.forEach((_value) => {
            _result.push(`${key}[]=${_value}`)
          })
      }
    } else {
      _result.push(`${key}=${value}`)
    }
  }
  return _result.length ? prefix + _result.join('&') : ''
}

/**
 * 处理 通用完成页面跳转参数设置
 */
export function toCompletePage(pageName) {
  wx.redirectTo({
    url: `${SUB_PAGES.Complete.INDEX.router}${queryParams({pageName})}`,
  })
}